package hibernate;

import hibernate.billStream.*;
import hibernate.roomSystem.*;
import hibernate.clientAccount.*;
import hibernate.administratorAccount.*;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class HibernateInitializer{
	
	private static SessionFactory factory=null;
	private static Configuration cfg=null;
	private static final String UNINITIALIZED="UNINITIALIZED",
								INITIALIZED="INITIALIZED",
								FAILED="FAILED";
	private static String state=UNINITIALIZED;
	
	private static void initialize(){
		if(state == INITIALIZED)
			return;
		
		try{
		cfg=new Configuration()
		.setProperty("hibernate.connection.driver_class", "org.apache.derby.jdbc.EmbeddedDriver")
		.setProperty("hibernate.connection.password", "root")
		.setProperty("hibernate.connection.url", "jdbc:derby:c:/db")
		.setProperty("hibernate.connection.username", "root")
		.setProperty("hibernate.dialect", "org.hibernate.dialect.DerbyDialect")
		.setProperty("hibernate.default_schema", "APP")
		.setProperty("show_sql","true");
		
		cfg
		   .addClass(Employee.class)
		   .addClass(Mapping.class)
		   .addClass(EmployeeInfo.class)
		   .addClass(Salary.class)
		   .addClass(AttendenceInfo.class)
		   .addClass(AttendenceRecord.class)
		   
		   .addClass(ServiceWrapper.class)
		   .addClass(ServiceCatagory.class)
		   .addClass(ServiceRec.class)
		   .addClass(CorporationEntity.class)
		   .addClass(CorpInfo.class)
		   .addClass(Bill.class)
		   .addClass(PaymentInfo.class)
		   .addClass(AccommodatingRec.class)
		   
		   .addClass(AbstractClient.class)
		   .addClass(ClientBasicInfo.class)
		   .addClass(VIPClient.class)
		   .addClass(ClientVIPInfo.class)
		   
		   .addClass(Room.class)
		   .addClass(RoomState.class)
		   .addClass(RoomType.class)
		   .addClass(ReservationForm.class);
		   //.setProperty(Environment.HBM2DDL_AUTO, "create");
		
		factory=cfg.buildSessionFactory();
		state=INITIALIZED;
		}catch(Throwable e){
			e.printStackTrace();
			state=FAILED;
		}
	}
	
	public static Session getSession(){
		if(state == FAILED)
			return null;
		
		if(state == UNINITIALIZED)
			initialize();
		
		if(state == INITIALIZED)
			return factory.openSession();
		else return null;
	}
	
	public static Transaction getTransaction(){
		if(state == FAILED)
			return null;
		
		if(state == UNINITIALIZED)
			initialize();
		
		if(state == INITIALIZED)
			return factory.openSession().beginTransaction();
		else return null;
	}
	
	public static void forceInitialize(){
		if(state != INITIALIZED)
			initialize();
	}
}